package com.develope.plant.service;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.AsyncTask;

import com.develope.plant.Constant.ERROR;
import com.develope.plant.utils.Logger;

public class AsyncSoapTask extends AsyncTask<String, Void, String>{
	private int errorCode = ERROR.UNKNOWN;
	private HttpHandler httpHandler;
	public AsyncSoapTask(HttpHandler httpHandler){
		this.httpHandler = httpHandler;
	}
	
	@Override
	protected String doInBackground(String... arg0) {
		SoapObject request = new SoapObject(SoapHelper.NAMESPACE, httpHandler.operation);
		if(httpHandler.params != null) {
			request.addProperty(httpHandler.params);
		}

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;

		envelope.setOutputSoapObject(request);

		HttpTransportSE httpTransport = new HttpTransportSE(SoapHelper.URL);
		Object response=null;
		try
		{
			httpTransport.call(SoapHelper.SOAP_ACTION, envelope);
			response = envelope.getResponse();
			errorCode = ERROR.OK;
		}
		catch (Exception exception)
		{
			response=exception.toString();
		}
		return response.toString();
	}
		
	@Override
	protected void onPostExecute(String result) {
		if (result ==  null) {
			Logger.error ("[ERR] httpTask: onPostExcute, the result is undefined!");
		}
		// TODO: post data to GUI
		httpHandler.onResponse(errorCode, result);
	}
	
	//--------------------------------------------------------------------------------------------
//	private static String convertInputStreamToString(InputStream inputStream, boolean closeInputStream)
//			throws IOException {
//		BufferedReader bufferedReader = new BufferedReader(
//				new InputStreamReader(inputStream));
//		String line = "";
//		String result = "";
//		while ((line = bufferedReader.readLine()) != null)
//			result += line;
//
//		if (closeInputStream) {
//			inputStream.close();	
//		}
//		return result;
//
//	}

}
